package com.cloudpivot.receivales.invoice.services;

import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.invoice.util.RsaEncryptionUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

@Service
@Slf4j
public class LdtWorkflowServiceResultsImpl  {

    @Value("${ldt.url}")
    private String url;

    @Value("${ldt.code}")
    private String code;

    @Value("${ldt.password}")
    private String password;
    /**
     * 推送开票结果
     * @param json 包含oa流程id、发票编号、开票结果
     * @param url
     * @return
     */
    public void pushResult(JSONObject json, String url){
        try {
            log.info("推送内容-->{}",json.toJSONString());
            CloseableHttpClient client = HttpClients.createDefault();
            StringEntity entity = new StringEntity(json.toJSONString(), "utf-8");
            entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            HttpPost con = new HttpPost(url);
            con.setHeader("Content-Type", "application/json");
            con.addHeader("Authorization",httpTool().get("data").getAsString());
            con.setEntity(entity);

            CloseableHttpResponse response = client.execute(con);
            HttpEntity httpEntity = response.getEntity();
            String resultStr = EntityUtils.toString(httpEntity);

            log.info("返回结果：" + resultStr);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取LDT系统token
     * @return 返回获取结果
     */
    private JsonObject httpTool(){
        RsaEncryptionUtil rsaEncryptionUtil = new RsaEncryptionUtil();
        Map<String,byte[]> map =rsaEncryptionUtil.rsaEncryption(code,password);
        JsonObject json = new JsonObject();
        json.addProperty("code",Base64.getEncoder().encodeToString(map.get("code")));
        json.addProperty("password",Base64.getEncoder().encodeToString(map.get("password")));
        Gson gson = new Gson();
        ldtResults jsonResult = new ldtResults();
        try {
            StringEntity entity = new StringEntity(json.toString(), "utf-8");
            entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost con = new HttpPost(url+"/loginByAuth");
            // 设置请求方法为POST
            con.setHeader("Content-Type", "application/json");
            con.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            con.setEntity(entity);

            // 写入请求体
            CloseableHttpResponse response = client.execute(con);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                String result = EntityUtils.toString(httpEntity, "utf-8");
                jsonResult = gson.fromJson(result, ldtResults.class);
            }
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("success", jsonResult.getSuccess());
            jsonObject.addProperty("msg", jsonResult.getMsg());
            jsonObject.addProperty("data", jsonResult.getData().toString());
            EntityUtils.consume(httpEntity);
            response.close();
            return jsonObject;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



}

/**
 *
 */
@Data
  class ldtResults {
    private Boolean success;
    private String msg;
    private Object data;
    // getters and setters
}

